//
//  STAlphaAnimator.m
//  STBest
//
//  Created by apple on 2017/8/29.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "STAlphaAnimator.h"
@interface STAlphaAnimator() <UIViewControllerAnimatedTransitioning>


@end
@implementation STAlphaAnimator


#pragma mark - UIViewControllerTransitioningDelegate -
// 提供显示时专场动画
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
//    self.isPresented = YES;
    
    return self;
}

// 提供消失时的专场动画
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
//    self.isPresented = NO;
    return self;
}

#pragma mark - UIViewControllerAnimatedTransitioning -
// 提供转场动画时长
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{
    
    return 0.5;
}

// 编写具体的转场动画
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
    
    // 1. 获取动画容器
    UIView *containerView = [transitionContext containerView];
    
    // 2. 获取源视图和目标视图
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    // 还能拿到视图控制器
    UIViewController *fromeVc = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    
    // 获取将要打开的视图
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    
    // 还能拿到将要的视图控制器
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    // 如果需要2个视图进行动画就必须都在视图容器内
    [containerView addSubview:toView];
    
    fromView.alpha = 1.0;
    toView.alpha = 0.0;
    [UIView animateWithDuration:[self transitionDuration:transitionContext]
                     animations:^{
                         fromView.alpha = 0.0;
                         toView.alpha = 1.0;
                     }
                     completion:^(BOOL finished) {
                         fromView.alpha = 0.0;
                         toView.alpha = 1.0;
                         // 一旦使用自定义专场动画，苹果API会事件冻结，所以当我们完成动画以后需要解除冻结
                         
                         [transitionContext completeTransition:YES];
                     }];
}
@end
